import {
  getUnStandProductProcessInfoByUnstandTypeId,
  addUnStandProductProcessInfo,
} from '@/services/design/productDesign';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-components';
import { Button, Form, Input, message, Modal, Row, Col, InputNumber } from 'antd';
import { CheckOutlined } from '@ant-design/icons';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import { Ellipsis } from '@/components/Ellipsis';
const unstandprocessInfo: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);

  const current_id = props.unStandTypeId;
  const current_bopcode = props.bopcode;
  const current_typecode = props.typecode;
  const current_typename = props.typename;
  const current_desc = props.desc;

  type DataSourceType = {
    id: React.Key;
    title?: string;
    readonly?: string;
    decs?: string;
    state?: string;
    created_at?: number;
    update_at?: number;
    children?: DataSourceType[];
  };

  const columns: ProColumns[] = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   valueType: 'index',
    //   width: 80,
    // },
    {
      title: '工序顺序',
      dataIndex: 'sequence',
      width: 90,
      align: 'center',
      sorter: true,
      readonly: true,
    },
    {
      title: '工序编号',
      dataIndex: 'processCode',
      width: 140,
      align: 'center',
      sorter: true,
      readonly: true,
    },
    {
      title: '工序名称',
      dataIndex: 'processName',
      width: 200,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      readonly: true,
    },
    {
      title: '是否生产工序',
      dataIndex: 'isProductionProcess',
      width: 140,
      align: 'center',
      sorter: true,
      // render: (text, record, _, action) => {
      //   return <div>{record.isProductionProcess == 1 ? '是' : '否'}</div>;
      // },
      readonly: true,
    },
    {
      title: '是否需要自检',
      dataIndex: 'showSelfInspection',
      width: 140,
      align: 'center',
      sorter: true,
      // render: (text, record, _, action) => {
      //   return <div>{record.isProductionProcess == 1 ? '是' : '否'}</div>;
      // },
      readonly: true,
    },
    {
      title: '标准工时(H)',
      dataIndex: 'standWorkHour',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.standWorkHour.toFixed(2)}</div>;
      },
      renderFormItem: ({ index }) => {
        return <InputNumber type="number" min={0.01} step="0.01" placeholder="保留两位小数" />;
      },
    },
    {
      title: '标准周期(天)',
      dataIndex: 'standCycle',
      align: 'center',
      sorter: true,
      render: (text) => {
        return <div>{text}</div>;
      },
      renderFormItem: ({ index }) => {
        return <InputNumber type="number" min={0} precision={0} placeholder="请输入正整数" />;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 100,
      fixed: 'right',
      align: 'center',
      render: (text, record, _, action) => [
        <a
          disabled={record.isProductionProcess !== '是'}
          key="editKey"
          onClick={() => {
            if(record.isProductionProcess !== '是'){
              message.error('非生产工序无需维护工时')
              return
            }
            action?.startEditable?.(record.processId);
            // setModalVisit(true);
            // setCreateOrUpdate(true);
            // form.setFieldsValue({
            //   bopCode: current_bopcode,
            //   unStandTypeCode: current_typecode,
            //   unStandTypeId: current_id,
            //   unStandTypeName: current_typename,
            //   processCode: record.processCode,
            //   processId: record.processId,
            //   processName: record.processName,
            //   sequence: record.sequence,
            //   standWorkHour: record.standWorkHour,
            //   standCycle: record.standCycle,
            //   isProductionProcess: record.isProductionProcess,
            // });
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  // 设置工时和周期
  const handleSubmit = async () => {
    setConfirmLoading(true);
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        res.standWorkHour = parseFloat(res.standWorkHour).toFixed(2);
        console.log(res, '弹窗数据');
        var process_para = new Object();
        process_para.bopCode = res.bopCode;
        process_para.unStandTypeCode = res.unStandTypeCode;
        process_para.unStandTypeId = res.unStandTypeId;
        process_para.unStandTypeName = res.unStandTypeName;
        process_para.bopPocessWorkHourAndCycleList = [res];
        console.log(process_para, '参数数据');
        const result = await addUnStandProductProcessInfo(process_para);
        if (result != null) {
          message.success('工时周期修改成功');
        }
        setConfirmLoading(false);
        setModalVisit(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading(false);
      });
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <EditableProTable<DataSourceType>
        rowKey="processId"
        headerTitle="非标柜体工时周期维护"
        actionRef={actionRef} //用于触发刷新操作等，看api
        // maxLength={5}到了最大行数，新建按钮消失
        recordCreatorProps={false}
        loading={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="save_button"
            type="primary"
            icon={<CheckOutlined />}
            onClick={async () => {
              var process_para = new Object();
              process_para.bopCode = current_bopcode;
              process_para.unStandTypeCode = current_typecode;
              process_para.unStandTypeId = current_id;
              process_para.unStandTypeName = current_typename;
              process_para.unStandTypeDesc = current_desc;
              process_para.bopPocessWorkHourAndCycleList = [];
              dataSource.map((item: any, index: any) => {
                item.standWorkHour = parseFloat(item.standWorkHour).toFixed(2);
                item.isProductionProcess = item.isProductionProcess == '是' ? 1 : 0;
                item.showSelfInspection = item.showSelfInspection == '是' ? 1 : 0;
                process_para.bopPocessWorkHourAndCycleList.push(item);
              });
              // console.log(process_para,'process_para');
              const result = await addUnStandProductProcessInfo(process_para);
              if (result != null) {
                message.success('工时周期修改成功');
              }
              actionRef.current!.reload();
            }}
          >
            保存
          </Button>,
        ]}
        scroll={{ x: 570, y: 350 }}
        columns={columns}
        request={async (params = {}, sort, filter) => {
          const result = await getUnStandProductProcessInfoByUnstandTypeId({
            unStandTypeId: current_id,
          });
          result.data.bopPocessWorkHourAndCycle.map((item: any) => {
            item.isProductionProcess = item.isProductionProcess == 1 ? '是' : '否';
            item.showSelfInspection = item.showSelfInspection == 1 ? '是' : '否';
          });
          console.log(result,'result');
          return {
            data: result.data.bopPocessWorkHourAndCycle,
            total: result.data.bopPocessWorkHourAndCycle.length,
            success: result.success,
          };
        }}
        value={dataSource}
        onChange={setDataSource}
        editable={{
          type: 'multiple',
          editableKeys,
          onSave: async (rowKey, data, row) => {},
          onChange: setEditableRowKeys,
          actionRender: (row, config, defaultDom) => {
            return [defaultDom.save, defaultDom.cancel];
          },
        }}
      />
      {/* <ProTable
        headerTitle="工序序列"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="processId" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
        ]}
        request={async (params = {}, sort, filter) => {
          // const res = { ...params, bopCode: current_bopcode };
          // const sorters = sortTran(sort);
          // const filters = filterTran(res);
          // const result = await getUnStandProductProcessInfoByUnstandTypeId({ ...params, sorters: sorters, filters: filters });
          const result = await getUnStandProductProcessInfoByUnstandTypeId({unStandTypeId: current_id});
          console.log(result,'result');
          return {
            data: result.data.bopPocessWorkHourAndCycle,
            total: result.data.bopPocessWorkHourAndCycle.length,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 570, y: 350 }}
        rowSelection={{}}
      /> */}
      <Modal
        title="非标柜体工时周期维护"
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        width={600}
        footer={null}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '130px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{}}
        >
          <Form.Item name="bopCode" label="bopCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="unStandTypeCode" label="unStandTypeCode" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="unStandTypeId" label="unStandTypeId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="unStandTypeName" label="unStandTypeName" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="processId" label="processId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item name="sequence" label="sequence" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="processName"
            label="工序名称"
            rules={[{ required: true, message: '请输入工序名称!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="processCode"
            label="工序编号"
            rules={[{ required: true, message: '请输入工序编号!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="isProductionProcess"
            label="属于生产工序"
            rules={[{ required: true, message: '请输入是否属于生产工序!' }]}
          >
            <Input
              disabled
              placeholder={form.getFieldValue().isProductionProcess == 1 ? '是' : '否'}
            />
          </Form.Item>
          <Form.Item
            name="showSelfInspection"
            label="是否需要自检"
            rules={[{ required: true, message: '请输入是否需要自检!' }]}
          >
            <Input
              disabled
              placeholder={form.getFieldValue().showSelfInspection == 1 ? '是' : '否'}
            />
          </Form.Item>
          <Form.Item
            name="standWorkHour"
            label="标准工时"
            rules={[{ required: true, message: '请输入标准工时!' }]}
          >
            <InputNumber min={0} max={1000000} width={380} step="0.01" addonAfter="h" stringMode />
          </Form.Item>
          <Form.Item
            name="standCycle"
            label="标准周期"
            rules={[{ required: true, message: '请输入标准周期!' }]}
          >
            <InputNumber min={0} max={1000000} width={380} step="1" addonAfter="天" stringMode />
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default unstandprocessInfo;
